<?php
/**
 * @package MicroPDO
 */
/**
 * @package MicroPDO
 * @author Lukasz Stosik <lstosik@gmail.com>
 * @license http://www.opensource.org/licenses/lgpl-3.0.html GNU Lesser General Public License
 */
class MicroPDO_DataObject {
    /** @var MicroPDO_PDO */
    protected $pdo;
    protected $tableName;
    protected $values;
    protected $changed;
    function __construct($tableName, $pdo) {
	$this->tableName = $tableName;
	$this->pdo = $pdo;
	$this->values = array();
	$this->changed = array();
    }
    /**
     * @param mixed $argument
     * @param mixed $value
     */
    function get($argument, $value = null) {
	if ($value == null) {
	    $value = $argument;
	    $argument = 'id';
	}
	$this->values = $this->pdo->getRow('select * from '.$this->tableName.' where '.$argument.' = ?', $value);
	$this->changed = array();
    }
    public function __get($name) {
	return $this->values[$name];
    }
    public function __isset($name) {
	return isset($this->values[$name]);
    }
    public function __unset($name) {
	unset($this->values[$name]);
    }
    public function __set($name,  $value) {
	$this->values[$name] = $value;
	$this->changed[$name] = true;
    }
    public function insert() {
	$cols = array_keys($this->values);
	$placeholders = array_fill(0, count($this->values), '?');
	$sql = "insert into ".$this->tableName." (".implode(',',$cols).") values (".implode(',', $placeholders).")";
	$this->pdo->exec($sql, array_values($this->values));
	return $this->pdo->lastInsertId();
    }
}

